package me.spring.cloud.components.starter.oauth2.backend.entrypoint;

import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import me.spring.cloud.common.components.oauth2.userdetails.exception.code.AuthoritiesCode;
import me.spring.cloud.common.components.response.util.CommonResponseUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;

/**
 * @description: 用于client校验及token校验失败返回信息
 * @author: luffy
 * @create: 2018-08-15 14:28
 **/
public class Oauth2ExceptionEntryPoint implements AuthenticationEntryPoint {

  @Autowired
  private ObjectMapper objectMapper;

  @Override
  public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException)
      throws IOException, ServletException {

    response.setContentType("application/json;charset=UTF-8");
    response.setStatus(HttpServletResponse.SC_OK);
    response.getWriter().write(
        objectMapper.writeValueAsString(CommonResponseUtil.error(AuthoritiesCode.TOKEN_INVALID)));
  }
}
